#!/usr/bin/env Rscript
out0 <- read.table("CAFolder/ca2logs/0.out", skip=1)
out1 <- read.table("CAFolder/ca2logs/1.out", skip=1)
out2 <- read.table("CAFolder/ca2logs/2.out", skip=1)
out3 <- read.table("CAFolder/ca2logs/3.out", skip=1)

getT <- function(out0,out1,out2,out3)
{
	Ci1 <- length(out0[,'V11'])
	Ci2 <- length(out1[,'V11'])
	Ci3 <- length(out2[,'V11'])
	Ci4 <- length(out3[,'V11'])
	Ci <- c(Ci1, Ci2, Ci3, Ci4)
	return (min(Ci))
}

getCo <- function(filename, searchword)
{
	text <- readLines(filename,encoding="UTF-8")
	C0 <- length(grep(searchword, text))
	return(C0)
}

getXo <- function(Co, time)
{
	return(Co/time)
}

getBusyTime <- function(data)
{
	average <- mean(data[,'V11'])
	return (100 - average)
}

CalcMaxThroughput <- function(Di)
{
	maxThroughput <- 1/max(Di)
	return(maxThroughput)
}

getBi <- function(out0,out1,out2,out3,Time)
{
	B1 <- Time * (getBusyTime(out0)/100)
	B2 <- Time * (getBusyTime(out1)/100)
	B3 <- Time * (getBusyTime(out2)/100)
	B4 <- Time * (getBusyTime(out3)/100)

	B0 <- c(B1, B2, B3, B4)

	return(B0)
}

getUi <- function(Bi, Time)
{
	U1 <- Bi[1]/Time
	U2 <- Bi[2]/Time
	U3 <- Bi[3]/Time
	U4 <- Bi[4]/Time

	U0 <- c(U1, U2, U3, U4)
	return(U0)
}

getDi <- function(Ui, X0)
{
D1 <- Ui[1]/X0
D2 <- Ui[2]/X0
D3 <- Ui[3]/X0
D4 <- Ui[4]/X0

D0 <- c(D1, D2, D3, D4)

return(D0)
}

UpperAsymptoticPlotGraph <- function(max,di)
{
	print("Plotting...")

	vec <- numeric(0)
	
	for(j in 1:100)
	{
		temp1 <- min(1/max(di),j/sum(di))
		vec <- c(vec,temp1)
	}
	plot(vec,main="Xo <= min( 1/maxDi, N/sum(Di) )", xlab="N (Concurrent Users)", ylab="Xo", pch=".",type="o",col="red",ylim=c(0,3))
	abline(h=max, lty = "dashed",v=1)
	 legend("topright",lty=c("dashed","solid"), 
        col = c("black","red"), 
        legend = c("Max Xo","min(1/maxDi,N/sum(Di)"))


}

increasePerformance <- function(data)
{
	data[1] <- data[1] * (1 - 0.25)
	data[3] <- data[3] * (1 - 0.25)
	return(data)
}

T <- getT(out0,out1,out2,out3)

C0 <- getCo("./CAFolder/ca2logs/log.dat", "processed")

X0 <- getXo(C0,T)

Bi <- getBi(out0,out1,out2,out3,T)

Ui <- getUi(Bi, T)

Di <- getDi(Ui, X0)

maxXo <- CalcMaxThroughput(Di)

UpperAsymptoticPlotGraph(maxXo,Di)

pdf(file='./CAReport.pdf')

print("T:")
print(T)

print("Co:")
print(C0)

print("Xo:")
format(X0,digits=4,nsmall=0)

print("Bi:")
format(Bi, digits=1,nsmall=0)

print("Ui:")
format(Ui,digits=2,nsmall=0)

print("Di:")
format(Di,digits=2,nsmall=0)

print("max Xo ( throughput ):")
format(maxXo,digits=6,nsmall=0)

print("Di:")
Di <- increasePerformance(Di)
format(Di,digits=2,nsmall=0)

maxXo <- CalcMaxThroughput(Di)
print("max Xo ( throughput ):")
format(maxXo,digits=6,nsmall=0)

UpperAsymptoticPlotGraph(maxXo,Di)
dev.off()
